// news-system-modern/src/store/index.ts
import { configureStore } from '@reduxjs/toolkit';
import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import { combineReducers } from '@reduxjs/toolkit';
import settingsReducer from './features/settingsSlice';
import collapsedReducer from './features/collapsedSlice';
import loadingReducer from './features/loadingSlice';
import userReducer, { setUser, clearUser } from './features/userSlice';
import globalReducer from './features/globalSlice';
import type { User } from '../types';
import { setDispatch } from '../utils/auth';

/**
 * 全局状态管理
 * 基于Redux Toolkit构建的状态管理系统
 */

// 合并所有reducer
const rootReducer = combineReducers({
  user: userReducer,
  global: globalReducer,
  settings: settingsReducer,
  collapsed: collapsedReducer,
  loading: loadingReducer
});

/**
 * Redux持久化配置
 * 用于在页面刷新后恢复状态
 */
const persistConfig = {
  key: 'root', // 存储在localStorage中的键名
  storage,     // 存储引擎
  whitelist: ['user', 'settings', 'collapsed', 'loading'], // 需要持久化的状态
  throttle: 1000, // 节流时间，防止频繁写入localStorage
  debug: process.env.NODE_ENV === 'development', // 仅在开发环境启用调试
};

/**
 * 创建持久化reducer
 * 将reducer与持久化配置结合
 */
const persistedReducer = persistReducer(persistConfig, rootReducer);

/**
 * 创建Redux store
 * 配置好的Redux状态存储和管理系统
 */
export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      // 关闭序列化检查，以避免与某些复杂对象的冲突
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
      immutableCheck: false, // 关闭不可变性检查，提高性能
    }),
  // 启用Redux DevTools插件，便于开发调试
  devTools: process.env.NODE_ENV !== 'production',
});

// 创建持久化store对象，用于在React组件中提供持久化功能
export const persistor = persistStore(store);

// 为auth工具设置dispatch函数，解决循环依赖问题
setDispatch(store.dispatch);

// 导出用户操作函数
export const setUserAction = (user: User) => {
  store.dispatch(setUser(user));
};

export const clearUserAction = () => {
  store.dispatch(clearUser());
};

export const toggleCollapsed = () => ({
  type: 'app/toggleCollapsed'
});

// 设置主题
export const setTheme = (theme: string) => ({
  type: 'settings/changeThemeMode',
  payload: theme
});

// 定义RootState类型，用于类型检查
export type RootState = ReturnType<typeof store.getState>;

// 定义AppDispatch类型，用于强类型的dispatch函数
export type AppDispatch = typeof store.dispatch;

// 重新导出hooks和基础类型
export * from './hooks';
export * from './types';

// 统一导出所有状态管理功能